#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

int main() {
    // 命令链：cat file.txt | grep abc | wc -l
    char *cmds[][4] = {
        {"cat", "file.txt", NULL},
        {"grep", "abc", NULL},
        {"wc", "-l", NULL}
    };
    int cmd_count = 3;

    int prev_fd = -1; // 上一个管道的读端

    for (int i = 0; i < cmd_count; ++i) {
        int pipefd[2];
        if (i < cmd_count - 1 && pipe(pipefd) < 0) {
            perror("pipe");
            exit(1);
        }

        pid_t pid = fork();
        if (pid == 0) {
            // 子进程
            if (prev_fd != -1) {
                dup2(prev_fd, STDIN_FILENO);
                close(prev_fd);
            }
            if (i < cmd_count - 1) {
                close(pipefd[0]);
                dup2(pipefd[1], STDOUT_FILENO);
                close(pipefd[1]);
            }
            execvp(cmds[i][0], cmds[i]);
            perror("exec failed");
            exit(1);
        }

        // 父进程
        if (prev_fd != -1) close(prev_fd);
        if (i < cmd_count - 1) {
            close(pipefd[1]);
            prev_fd = pipefd[0];
        }
    }

    for (int i = 0; i < cmd_count; ++i) wait(NULL);
    return 0;
}

